package com.ycsj.goldmedalnewconcept.common.activity;

import android.content.Intent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.ycsj.common.base.BaseActivity;
import com.ycsj.common.base.BusInfo;
import com.ycsj.common.doubleclick.AntiShake;
import com.ycsj.common.utils.ScreenUtils;
import com.ycsj.common.utils.UiUtils;
import com.ycsj.common.view.scroll.MyGridView;
import com.ycsj.goldmedalnewconcept.R;
import com.ycsj.goldmedalnewconcept.common.adapter.UnitGvAdapter;
import com.ycsj.goldmedalnewconcept.common.bean.UnitGvInfo;
import com.ycsj.goldmedalnewconcept.common.util.LayoutUtils;
import com.ycsj.goldmedalnewconcept.teacher.activity.TeacherCreateHomeworkActivity;
import com.ycsj.goldmedalnewconcept.teacher.activity.TeacherTKAssignHomeworkActivity;
import com.ycsj.goldmedalnewconcept.view.MyScrollView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 单元选择界面
 * Created by Administrator on 2019/2/20 0020.
 */

public class ChooseUnitActivity extends BaseActivity {

    @BindView(R.id.scrollview)
    MyScrollView scrollView;
    @BindView(R.id.rl_contain)
    RelativeLayout rlContain;

    @BindView(R.id.rl_loading)
    RelativeLayout rl_loading;

    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.mgv)
    MyGridView mgv;

    //展示单元栏目的数据格式
    private List<UnitGvInfo> unitDatas;

    //背景图的设计宽高
    private int width = 750;
    private int height = 10672;

    //展示单元选项的GridView适配器
    private UnitGvAdapter gvAdapter;

    //用于存放所有布局参数
    private List<Integer> paramsMarginlefts;
    private List<Integer> paramsMargintops;
    private int screenWidth;
    //用于放置所有按钮的线性布局的高度
    private int llheight;

    //每个Unit单元的TextView的大小
    private int itemSize = 48;

    //添加Unit单元的布局参数
    private RelativeLayout.LayoutParams lp;

    @Override
    protected int getContentLayout() {
        return R.layout.activity_choose_new_unit;
    }

    @Override
    protected void init() {

        //沉浸式
        initStateBar();

        //初始化标题
        initTitle();

        //动态配置滚动布局的宽高
        initParamsBg();

        //初始化单元导航栏
        initGv();

        //动态计算每个按钮的布局参数宽和高
        initPositon();

        //每单元设置点击事件
        initClickEvent();

        //设置ScrollView的滚动监听事件
        initScrollListener();

    }

    /**
     * 初始化标题栏
     */
    private void initTitle() {

        tvTitle.setText("选择单元");

        if (rl_loading != null && rl_loading.getVisibility() == View.VISIBLE) {
            rl_loading.setVisibility(View.GONE);
        }

        if (rlContain != null && rlContain.getVisibility() != View.VISIBLE) {
            rlContain.setVisibility(View.VISIBLE);
        }
    }


    /**
     * 动态设置背景图的宽高
     */
    private void initParamsBg() {
        screenWidth = ScreenUtils.getScreenWidth(this);
        //计算高度,根据设计图的宽高比来动态设置宽高
        llheight = screenWidth * height / width;
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(screenWidth, llheight);
        rlContain.setLayoutParams(lp);
    }

    /**
     * 动态计算72个单元的布局宽和高
     */
    private void initPositon() {
        paramsMarginlefts = LayoutUtils.getMarinLefts(screenWidth);
        paramsMargintops = LayoutUtils.getMarinTops(llheight);

        //动态添加按钮布局
        if (paramsMarginlefts.size() != 0 && paramsMargintops.size() != 0) {
            for (int i = 1; i <= paramsMargintops.size(); i++) {
                TextView tv = (TextView) View.inflate(this, R.layout.unit_item_tv, null);
                tv.setTag((73 - i));
                lp = new RelativeLayout.LayoutParams(UiUtils.dp2px(itemSize), UiUtils.dp2px(itemSize));
                lp.topMargin = paramsMargintops.get(i - 1);
                lp.leftMargin = paramsMarginlefts.get(i - 1);
                tv.setText((73 - i) + "");
                //配置TextView的paddingleft和paddingtop,确保文字居中
                if (i > 63 && i <= paramsMargintops.size()) {
                    //文字为1到9时
                    tv.setPadding(UiUtils.dp2px(15), UiUtils.dp2px(7), 0, 0);
                } else {
                    //文字为两位数
                    tv.setPadding(UiUtils.dp2px(11), UiUtils.dp2px(7), 0, 0);
                }

                //这里还需要根据服务器返回的状态来设置Unit的背景以及是否可以点击
                rlContain.addView(tv, lp);
            }
        }
    }

    /**
     * 所有Unit单元的点击事件
     */
    private void initClickEvent() {
        int chlidCount = rlContain.getChildCount();
        for (int i = 0; i < chlidCount; i++) {
            final TextView tv = (TextView) rlContain.getChildAt(i);
            tv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    //点击以后跳转到携带单元号跳转到下个界面
                    int unitNumber = (int) tv.getTag();
                    //跳转到题库布置练习界面
                    Intent intent = new Intent(ChooseUnitActivity.this,
                            TeacherTKAssignHomeworkActivity.class);
                    intent.putExtra("unit", unitNumber);
                    startActivity(intent);
                }
            });
        }
    }

    /**
     * 初始化单元导航栏
     */
    private void initGv() {
        unitDatas = new ArrayList<>();
        UnitGvInfo oneUnitGvInfo = new UnitGvInfo(R.drawable.one_select, R.drawable.one_unselect, true);
        UnitGvInfo twoUnitGvInfo = new UnitGvInfo(R.drawable.two_select, R.drawable.two_unselect, false);
        UnitGvInfo threeUnitGvInfo = new UnitGvInfo(R.drawable.three_select, R.drawable.three_unselect, false);
        UnitGvInfo fourUnitGvInfo = new UnitGvInfo(R.drawable.four_select, R.drawable.four_unselect, false);
        unitDatas.add(oneUnitGvInfo);
        unitDatas.add(twoUnitGvInfo);
        unitDatas.add(threeUnitGvInfo);
        unitDatas.add(fourUnitGvInfo);

        gvAdapter = new UnitGvAdapter(this, unitDatas, R.layout.item_gv_unit);

        mgv.setAdapter(gvAdapter);

        //条目点击事件
        mgv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {

                //根据点击的条目让ScrollView滚动到指定位置
                switch (position) {
                    case 0:
                        //滚动到底部
                        scrollView.fullScroll(ScrollView.FOCUS_DOWN);
                        break;
                    case 1://顶部停留在19单元
                        scrollView.post(new Runnable() {
                            @Override
                            public void run() {
                                TextView tv = (TextView) rlContain.getChildAt(53);
                                scrollView.smoothScrollTo(0, tv.getTop() - ScreenUtils.getScreenHeight(ChooseUnitActivity.this) + UiUtils.dp2px(80));
                            }
                        });
                        break;
                    case 2://37
                        scrollView.post(new Runnable() {
                            @Override
                            public void run() {
                                TextView tv = (TextView) rlContain.getChildAt(35);
                                scrollView.smoothScrollTo(0, tv.getTop() - ScreenUtils.getScreenHeight(ChooseUnitActivity.this) + UiUtils.dp2px(80));
                            }
                        });
                        break;
                    case 3:
                        //滚动到顶部
                        scrollView.fullScroll(ScrollView.FOCUS_UP);
                        break;
                }

                if (unitDatas.get(position).isSelected) {
                    return;
                } else {
                    sysGvState(position);
                }
            }
        });
    }

    /**
     * ScrollView的滚动监听事件
     */
    private void initScrollListener() {

        //初次进入的时候让ScrollView滚动到底部
        scrollView.post(new Runnable() {
            @Override
            public void run() {
                scrollView.fullScroll(ScrollView.FOCUS_DOWN);
            }
        });

        //滚动监听
        scrollView.setOnScrollListener(new MyScrollView.OnScrollListener() {
            @Override
            public void onScroll(int scrollY) {
                //判断滚动距离,同步顶部Unit单元的同步状态

                TextView tv53 = (TextView) rlContain.getChildAt(53); //对应19
                int top53Distance = tv53.getTop() - ScreenUtils.getScreenHeight(ChooseUnitActivity.this) + UiUtils.dp2px(80);

                TextView tv35 = (TextView) rlContain.getChildAt(35);//对应3
                int top35Distance = tv35.getTop() - ScreenUtils.getScreenHeight(ChooseUnitActivity.this) + UiUtils.dp2px(80);


                TextView tv17 = (TextView) rlContain.getChildAt(17);//对应3
                int top17Distance = tv17.getTop() - ScreenUtils.getScreenHeight(ChooseUnitActivity.this) + UiUtils.dp2px(80);

                //从下往上滑
                if (scrollY > top53Distance) {
                    //1-1选中
                    sysGvState(0);
                } else if (scrollY > top35Distance) {
                    //1-2选中,滚动距离为9978-5615 对应的是53-35
                    sysGvState(1);
                } else if (scrollY > top17Distance) {
                    //1-3选中,滚动距离为5615-221 对应的是35-17
                    sysGvState(2);
                } else if (scrollY > 0) {
                    //1-4选中
                    sysGvState(3);
                }
            }
        });
    }

    /**
     * @param pos
     */
    private void sysGvState(int pos) {
        for (int i = 0; i < unitDatas.size(); i++) {
            if (i == pos) {
                unitDatas.get(i).isSelected = true;
            } else {
                unitDatas.get(i).isSelected = false;
            }
        }
        gvAdapter.notifyDataSetChanged();
    }

    /**
     * 点击事件
     *
     * @param v
     */
    @OnClick({R.id.iv_back})
    public void clickEvent(View v) {
        if (AntiShake.check(v)) {
            ToastUtils.showShort("点击过快");
        } else {
            switch (v.getId()) {
                case R.id.iv_back:
                    //返回
                    finish();
                    break;
            }
        }
    }


    /**
     * 事件处理
     *
     * @param busInfo
     */
    @Override
    public void busEvent(BusInfo busInfo) {
        super.busEvent(busInfo);
        if (null != busInfo) {

            //草稿箱保存成功及练习发布成功，关闭单元选择界面
            if (busInfo.type == TeacherCreateHomeworkActivity.SUBMITSUC || busInfo.type == TeacherTKAssignHomeworkActivity.SUBMITREF) {
                finish();
            }
        }
    }
}
